from django.test import TestCase

# Create your tests here.

from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from .models import ImageSave  # 替换为你的模型

class ImageUploadTestCase(APITestCase):
    def setUp(self):
        # 如果需要，可以在这里设置初始化数据
        pass

    def test_image_upload(self):
        # 准备图片文件
        with open(r"D:\add_todesk\Pictures\Sample Pictures\jd.jpg", 'rb') as img:
            test_image = SimpleUploadedFile(
                name='test_image.jpg',
                content=img.read(),
                content_type='image/jpeg'
            )

        # 模拟发送POST请求
        url = reverse('192.168.31.93:8000/api/picture/picturesave')  # 替换为实际的上传接口URL名称
        data = {'image': test_image}
        response = self.client.post(url, data, format='multipart')

        # 检查响应状态码是否为201 Created
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # 验证数据库中是否保存了图片
        self.assertEqual(ImageSave.objects.count(), 1)  # 替换为你的模型
        self.assertTrue(ImageSave.objects.filter(image='path_to_uploaded_image/test_image.jpg').exists())

        # 验证响应中的数据
        self.assertIn('image', response.data)
        self.assertTrue(response.data['image'].endswith('test_image.jpg'))

